import React, { useEffect } from 'react';
import { EventBusImpl } from '../common';
import { ApplicationService } from '../common/application.service';
import { TerminalInternalService } from '../terminal-next/browser/terminal.internal.service';
import { TerminalGroupViewService } from '../terminal-next/browser/terminal.view';
import { TerminalClientFactory } from '../terminal-next/browser/terminal.client';
import { TerminalErrorService } from '../terminal-next/browser/terminal.error';
import { TerminalApiService } from '../terminal-next/browser/terminal.api';
import TerminalView from '../terminal-next/browser/component/terminal.view';
import { TerminalController } from '../terminal-next/browser/terminal.controller';

const TerminalComponent: React.FC = () => {
  const eventBus = new EventBusImpl();
  const appService = new ApplicationService({
    workspaceDir: '',
    extWorkerHost: '',
    isElectronRenderer: true,
  });
  const terminalInternalService = new TerminalInternalService();
  const terminalGroupViewService = new TerminalGroupViewService(
    terminalInternalService
  );

  let controller: TerminalController;

  const clientFactory = (widget, options) =>
    TerminalClientFactory.createClient2(
      terminalInternalService,
      controller!,
      eventBus,
      widget,
      options
    );

  controller = new TerminalController(
    eventBus,
    terminalGroupViewService,
    clientFactory,
    terminalInternalService,
    appService
  );

  const terminalErrorService = new TerminalErrorService(
    terminalInternalService,
    controller,
    terminalGroupViewService
  );

  const terminalApiService = new TerminalApiService(
    controller,
    terminalGroupViewService,
    terminalInternalService
  );

  const effectRan = React.useRef(false);

  // 核心逻辑：显示终端
  useEffect(() => {
    if (effectRan.current) return; // 跳过第二次调用
    effectRan.current = true;

    controller.viewReady.promise.then(() => {
      setTimeout(() => {
        terminalApiService.createTerminal({});
      }, 0);
    });
  }, []);

  return (
    <div style={{ height: '30vh', background: '#000' }}>
      <TerminalView
        controller={controller}
        errorService={terminalErrorService}
        view={terminalGroupViewService}
      />
    </div>
  );
};

export default TerminalComponent;
